import 'package:flutter/material.dart';
import 'package:logger/logger.dart';

class ValueListenableRoute extends StatefulWidget {
  const ValueListenableRoute({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _ValueListenableRouteState();
}

class _ValueListenableRouteState extends State<ValueListenableRoute> {
  final logger = Logger(printer: LogfmtPrinter());

  final _counter = ValueNotifier<int>(0);

  static const double textScaleFactor = 1.5;

  @override
  Widget build(BuildContext context) {
    logger.i('build');
    return Scaffold(
      appBar: AppBar(
        title: const Text('ValueListenableBuilder 测试'),
      ),
      body: Center(
        child: ValueListenableBuilder<int>(
          builder: (context, value, child) {
            // builder 方法只会在 _counter 变化时被调用
            return Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                child!,
                Text('$value 次', textScaleFactor: textScaleFactor),
              ],
            );
          },
          valueListenable: _counter,
          child: const Text('点击了 ', textScaleFactor: textScaleFactor),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        // 点击后值 +1，触发 ValueListenableBuilder 重新构建
        onPressed: () => _counter.value += 1,
      ),
    );
  }
}
